-- 玩家模块
-- Author: Colocasia
-- Date: 2018-07-12

local class = require 'class';
local module = require 'module';
local account = require 'account';
local table = require 'us.table';
local log = require 'log';

---@class player : account
local M = class('player', account);

---常用函数引用
---@type fun table.merge @合并函数
local table_merge = table.merge;

---构造函数
---@param guid string @玩家GUID
function M:ctor(guid)
    self.super:ctor();
    module(self, "player_data");

    self:launch(guid);
end

---生成player信息
---@param result player @玩家信息
local function gen_player_info(result)
    return {
        name        = result.name,
        guid        = result.guid,
        head        = result.head,
        exp         = result.exp,
        char_list   = result.char_list,
    };
end

---使用GUID查询玩家
---@param guid string @玩家GUID
---@return table
function M:find_player_by_guid(guid)
    local result = self:exc_db_cmd('player', 'find_player_by_guid', guid);
    -- 账户不存在
    if not result then return end
    return gen_player_info(result);
end

---玩家进入游戏
function M:login()

    self:send_push({
        hello = "welcom to my game";
    })

    return self:full_info();
end

---玩家的公共信息
---@return player @公共信息
function M:public_info()
    return {
        server      = self.server,
        guid        = self.guid,
        name        = self.name,
        head        = self.head,
        exp         = self.exp,
        level       = self.level,
    };
end

---获取玩家的全部信息
---@return player @全部信息
function M:full_info()
    return table_merge({
        self:public_info(),
        {

        },
    })
end

---获取能否发送推送
---@return boolean
function M:can_push()
    return self.__fd and self.__push_func or false
end

---发送推送
---@param msg table @需要推送的消息
function M:send_push(msg, proto)
    if not self:can_push() then return end
    if not msg then return end
    self.__push_func(self.__fd, {
        proto_type = proto or 2,
        proto_name = "server_push",
        data = msg,
    })
end

---设置推送信息
---@param fd number @玩家fd地址
---@param push_func function @推送函数
---@return boolean
function M:set_push_info(fd, push_func)
    self.__fd = fd
    self.__push_func = push_func
    return true
end


---添加角色
---@param char_id number @角色ID
function M:add_character(char_id)
    return self:exc_db_cmd('player', 'player_insert_character', self.guid, char_id);
end

return M;
